import { removeUserInfo } from "./cookieLogin";
import { getToken } from "./cookieLogin";
import { message } from "antd";
import { createBrowserHistory } from "history";
// history插件，在无useNavigate下进行地址跳转
import axios from "axios";

const history = createBrowserHistory()

// 拦截器相关   npm官网 axios下方    instance举例 和 Interceptors举例

const request = axios.create({
    baseURL: import.meta.env.VITE_BASE_URL,
    timeout: 6000,
    // headers: {'X-Custom-Header': 'foobar'}
});

// Add a request interceptor 添加拦截器
request.interceptors.request.use(function (config) {
    if (getToken()) {
        config.headers.accessToken = getToken()
    }
    // Do something before request is sent
    return config;
},
    function (error) {
        // Do something with request error
        return Promise.reject(error);
    }
);

// Add a res interceptor
request.interceptors.response.use(function (res) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with res data
    switch (res.data.code) {
        case 403:
            // 登录状态过期 提示    去登录页页面
            message.error('登录状态过期', 2, () => {
                removeUserInfo()
                history.replace('/login')
                // history插件的bug? 需要刷新下
                history.go(0)
            })
            break;

        case 405:

            break;

        default:
            break;
    }
    return res;
},
    function (error) {
        // Any status codes that falls outside the range of 2xx cause this function to trigger
        // Do something with res error
        return Promise.reject(error);
    }
);
export default request